package com.wgl.sms.controller;

import com.wgl.sms.service.MsmService;
import com.wgl.sms.util.RandomUtil;
import com.wgl.yygh.result.Result;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author wgl
 * @version 1.0.0
 * @ClassName MsmApiController.java
 * @Description TODO
 * @createTime 2022年02月09日 16:26:00
 */
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Resource
    private MsmService msmService ;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @GetMapping("/send/{phone}")
    public Result send(@PathVariable String  phone){
        //先从redis获取验证码
        String code = (String) redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //获取不到就生成验证码
        String sixBitRandom = RandomUtil.getSixBitRandom();
        boolean send = msmService.send(phone, sixBitRandom);
        if (send){
            redisTemplate.opsForValue().set(phone,sixBitRandom,5, TimeUnit.MINUTES);
            return Result.ok();
        }
        return Result.fail().message("发送信息失败");

    }
}
